/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.project.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.common.utils.Collections3;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.modules.project.entity.ProjectMember;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.project.entity.ProjectInfo;
import com.jeeplus.modules.project.service.ProjectInfoService;

/**
 * 项目信息Controller
 *
 * @author 卢经纬
 * @version 2019-04-10
 */
@Controller
@RequestMapping(value = "${adminPath}/project/projectInfo")
public class ProjectInfoController extends BaseController {

    @Autowired
    private ProjectInfoService projectInfoService;
    @Autowired
    private OfficeService officeService;

    @ModelAttribute
    public ProjectInfo get(@RequestParam(required = false) String id) {
        ProjectInfo entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = projectInfoService.get(id);
        }
        if (entity == null) {
            entity = new ProjectInfo();
        }
        return entity;
    }

    /**
     * 添加项目列表数据
     */
    @ResponseBody
    @RequiresPermissions("project:projectInfo:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(ProjectInfo projectInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<ProjectInfo> page = projectInfoService.findPage(new Page<ProjectInfo>(request, response), projectInfo, true);
        return getBootstrapData(page);
    }

    /**
     * 添加项目列表页面
     */
    @RequiresPermissions("project:projectInfo:list")
    @RequestMapping(value = {"list", ""})
    public String list() {
        return "modules/project/projectInfoList";
    }

    /**
     * 查看，增加，编辑添加项目表单页面
     */
    @RequiresPermissions(value = {"project:projectInfo:view",
            "project:projectInfo:add", "project:projectInfo:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(ProjectInfo projectInfo, Model model) {
        model.addAttribute("projectInfo", projectInfo);
        return "modules/project/projectInfoForm";
    }

    /**
     * 保存添加项目
     */
    @RequiresPermissions(value = {"project:projectInfo:add",
            "project:projectInfo:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public String save(ProjectInfo projectInfo, Model model,
                       RedirectAttributes redirectAttributes) throws Exception {
        if (!beanValidator(model, projectInfo)) {
            return form(projectInfo, model);
        }
        if (!projectInfo.getIsNewRecord()) {// 编辑表单保存
            ProjectInfo t = projectInfoService.get(projectInfo.getId());// 从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(projectInfo, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
            projectInfoService.save(t);// 保存
        } else {// 新增表单保存
            System.out.println(new Gson().toJson(projectInfo));
            projectInfoService.save(projectInfo);// 保存
        }
        addMessage(redirectAttributes, "保存添加项目成功");
        return "redirect:" + Global.getAdminPath()
                + "/project/projectInfo/?repage";
    }

    /**
     * 微信保存添加项目
     */
    @RequestMapping(value = "weChatSave")
    public String weChatSave(String idsArr, ProjectInfo projectInfo,
                             Model model, RedirectAttributes redirectAttributes)
            throws Exception {
        ProjectMember projectMember;
        User user;
        if (!beanValidator(model, projectInfo)) {
            return form(projectInfo, model);
        }
        if (!projectInfo.getIsNewRecord()) {// 编辑表单保存
            ProjectInfo t = projectInfoService.get(projectInfo.getId());// 从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(projectInfo, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
            projectInfoService.save(t);// 保存
        } else {// 新增表单保存
            String[] ids = idsArr.split(",");
            for (int i = 0; i < ids.length; i++) {
                projectMember = new ProjectMember();
                user = new User();
                user.setId(ids[i]);
                projectMember.setTuser(user);
                projectMember.setId("");
                projectInfo.getProjectMemberList().add(projectMember);
            }
            System.out.println(new Gson().toJson(projectInfo));
            projectInfoService.save(projectInfo);// 保存
        }
        addMessage(redirectAttributes, "保存添加项目成功");
        return "redirect:" + Global.getAdminPath()
                + "/project/projectInfo/weChatAdd?repage";
    }

    /**
     * 微信项目添加页面
     */

    @RequestMapping(value = "/weChatAdd")
    public String weChatAdd(ProjectInfo projectInfo,
                            HttpServletRequest request, HttpServletResponse response,
                            Model model) {
        return "modules/project/projectInfoWeChatAdd";
    }

    /**
     * 微信项目列表页面
     */
    @RequiresPermissions("project:projectInfo:weChatList")
    @RequestMapping(value = "/weChatList")
    public String weChatList(ProjectInfo projectInfo,
                             HttpServletRequest request, HttpServletResponse response,
                             Model model) {
        // 判断权限如果是项目经理或者项目成员或者超级管理员或者部门负责人才可以看到项目
        List<ProjectInfo> list = projectInfoService.findList(projectInfo, true);
        model.addAttribute("list", list);
        model.addAttribute("projectInfo", projectInfo);
        return "modules/project/projectInfoWeChatList";
    }

    /**
     * 微信项目列表页面
     */
    @RequestMapping(value = "/flashWeChatList")
    public String flashWeChatList(List<User> userList,
                                  HttpServletRequest request, HttpServletResponse response,
                                  Model model) {
        // 判断权限如果是项目经理或者项目成员或者超级管路员才可以看到自己的项目
        model.addAttribute("userList", userList);
        StringBuffer idsArr = new StringBuffer();
        for (int i = 0; i < userList.size(); i++) {
            if (i == 0) {
                idsArr.append(userList.get(i).getId());
            } else {
                idsArr.append("," + userList.get(i).getId());
            }

        }
        model.addAttribute("idsArr", idsArr.toString());
        return "modules/project/projectInfo/WeChatList?repage";
    }

    /**
     * 删除添加项目
     */
    @RequiresPermissions("project:projectInfo:del")
    @RequestMapping(value = "delete")
    public String delete(ProjectInfo projectInfo,
                         RedirectAttributes redirectAttributes) {
        projectInfoService.delete(projectInfo);
        addMessage(redirectAttributes, "删除添加项目成功");
        return "redirect:" + Global.getAdminPath()
                + "/project/projectInfo/?repage";
    }

    /**
     * 批量删除添加项目
     */
    @RequiresPermissions("project:projectInfo:del")
    @RequestMapping(value = "deleteAll")
    public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            projectInfoService.delete(projectInfoService.get(id));
        }
        addMessage(redirectAttributes, "删除添加项目成功");
        return "redirect:" + Global.getAdminPath()
                + "/project/projectInfo/?repage";
    }

    /**
     * 导出excel文件
     */
    @RequiresPermissions("project:projectInfo:export")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(ProjectInfo projectInfo,
                             HttpServletRequest request, HttpServletResponse response,
                             RedirectAttributes redirectAttributes) {
        try {
            String fileName = "添加项目" + DateUtils.getDate("yyyyMMddHHmmss")
                    + ".xlsx";
            Page<ProjectInfo> page = projectInfoService.findPage(
                    new Page<ProjectInfo>(request, response, -1), projectInfo);
            new ExportExcel("添加项目", ProjectInfo.class)
                    .setDataList(page.getList()).write(response, fileName)
                    .dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出添加项目记录失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath()
                + "/project/projectInfo/?repage";
    }

    /**
     * 导入Excel数据
     */
    @RequiresPermissions("project:projectInfo:import")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file,
                             RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<ProjectInfo> list = ei.getDataList(ProjectInfo.class);
            for (ProjectInfo projectInfo : list) {
                try {
                    projectInfoService.save(projectInfo);
                    successNum++;
                } catch (ConstraintViolationException ex) {
                    failureNum++;
                } catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条添加项目记录。");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条添加项目记录"
                    + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入添加项目失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath()
                + "/project/projectInfo/?repage";
    }

    /**
     * 下载导入添加项目数据模板
     */
    @RequiresPermissions("project:projectInfo:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response,
                                     RedirectAttributes redirectAttributes) {
        try {
            String fileName = "添加项目数据导入模板.xlsx";
            List<ProjectInfo> list = Lists.newArrayList();
            new ExportExcel("添加项目数据", ProjectInfo.class, 1).setDataList(list)
                    .write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath()
                + "/project/projectInfo/?repage";
    }

    /**
     * 成员选择 -- 打开项目成员选择对话框
     *
     * @param idsArr
     * @param model
     * @return
     */
    @RequestMapping(value = "/usertomember")
    public String selectUserToMember(String idsArr, Model model) {
        if (StringUtils.isNoneBlank(idsArr)) {
            String[] isdArrs = idsArr.split(",");
            List<User> userList = new ArrayList<User>();
            for (int i = 0; i < isdArrs.length; i++) {
                userList.add(UserUtils.get(isdArrs[i]));
            }
            if (userList.size() > 0) {
                model.addAttribute("userList", userList);
                model.addAttribute("selectIds",
                        Collections3.extractToString(userList, "name", ","));
            }
        }
        model.addAttribute("officeList", officeService.findList(false));
        return "modules/sys/selectUserToMember";
    }


}